package com.jiazhong.example.project.bookstore.front.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiazhong.example.project.bookstore.commons.bean.Order;
import com.jiazhong.example.project.bookstore.commons.bean.OrderItem;
import com.jiazhong.example.project.bookstore.commons.config.JwtConfig;
import com.jiazhong.example.project.bookstore.commons.handler.OrderSaveException;
import com.jiazhong.example.project.bookstore.commons.mapper.OrderItemMapper;
import com.jiazhong.example.project.bookstore.commons.mapper.OrderMapper;
import com.jiazhong.example.project.bookstore.commons.util.JsonResult;
import com.jiazhong.example.project.bookstore.commons.util.NumericUUIDGenerator;
import com.jiazhong.example.project.bookstore.commons.util.ResultTool;
import com.jiazhong.example.project.bookstore.front.service.OrderService;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.List;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private OrderItemMapper orderItemMapper;

    @Transactional(rollbackFor = {SQLException.class, OrderSaveException.class})
    public JsonResult addOrder(Order order, HttpServletRequest request) {
        // 添加订单
        long uuid = NumericUUIDGenerator.getNumericUUID();
        Claims claims = JwtConfig.parseJWT(request.getHeader("token"));
        String userId = claims.get("id").toString();
        order.setId(uuid + "");
        order.setUserId(userId);
        order.setStatus(1);
        int insert = orderMapper.insert(order);
        if (insert == 0) {
            throw new OrderSaveException("录入订单失败");
        }
        // 添加订单详情
        List<OrderItem> orderItems = order.getOrderItems();
        for (OrderItem orderItem : orderItems) {
            orderItem.setOrderId(order.getId());
            int row = orderItemMapper.insert(orderItem);
            if (row == 0) {
                throw new OrderSaveException("录入订单失败");
            }
        }
        return ResultTool.success(uuid + "");
    }
}
